import dto.Configure;

import java.io.*;
import java.util.Objects;

/**
 * @author sk.z
 */
public class ReadConfigure {

    private static final String fileName = "ddns-dynv6.ini";

    public static Configure read() throws InterruptedException {
        Configure result = new Configure();
        String root = System.getProperty("user.dir");

        File file = new File(root + File.separator + fileName);
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            String temp;
            String value;
            while ((temp = reader.readLine()) != null) {
                if (!temp.contains("=")) {
                    continue;
                }
                value = temp.substring(temp.indexOf("=") + 1).trim();
                if (temp.startsWith("zone")) {
                    result.setZone(value);
                } else if (temp.startsWith("token")) {
                    result.setToken(value);
                } else if (temp.startsWith("interval")) {
                    result.setInterval(Long.valueOf(value));
                } else if (temp.startsWith("website")){
                    result.addWebsite(value);
                }
            }
        } catch (FileNotFoundException e) {
            System.out.println("can not find the configure file :" + fileName);
            Thread.sleep(6000);
            System.exit(0);
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (Objects.isNull(result.getZone())) {
            System.out.println("configure lose : zone");
        }
        if (Objects.isNull(result.getToken())) {
            System.out.println("configure lose : token");
        }
        if (Objects.isNull(result.getInterval())) {
            System.out.println("configure lose : interval");
        }

        System.out.println("\nread configure success :");
        System.out.println("\tzone: " + result.getZone());
        System.out.println("\ttoken: "+ result.getToken());
        System.out.println("\tinterval: "+ result.getInterval());

        return result;
    }
}
